package day11;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

//a.有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池用一个数组int[] arr = {10,5,20,50,100,200,500,800,2,80,300};
//创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”，“抽奖箱2”，随机从arr数组中获取奖项元素并打印在控制台上,格式如下:
//抽奖箱1 又产生了一个 10 元大奖
//抽奖箱2 又产生了一个 100 元大奖
//.....
//按照每次将只能出现一次
public class Prize {
    static Integer[] arr = {10, 5, 20, 50, 100, 200, 500, 800, 2, 80, 300};
    ReentrantLock lock = new ReentrantLock();
    static List<Integer> list;

    static {
        list = new ArrayList<>(Arrays.asList(arr));
    }

    Random r = new Random();


    //每次抽奖的过程   通过方法编写  让其线程安全
    public void lucky() {
        try {
            String name = Thread.currentThread().getName();
            lock.lock();
            if (!list.isEmpty()) {
                int index = r.nextInt(list.size());
                System.out.println(name + "抽奖箱产生了" + list.remove(index) + "元的大奖");
                Thread.sleep(100);
                lock.unlock();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Prize p = new Prize();
        for (int i = 1; i <= 2; i++) {
            new Thread(() -> {
                while (!list.isEmpty()) {
                    p.lucky();
                }
            }, "抽奖箱:" + i).start();
        }
    }
}
